package info.liuxing.okhttp.cookie;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MemoryCookieStore
 *
 * @author liuxing (SE)
 * @summary MemoryCookieStore
 * @Copyright (c) 2017, Lianjia Group All Rights Reserved.
 * @since 2017-12-01 00:11
 */
public class MemoryCookieStore implements CookieJar {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemoryCookieStore.class);

    private final Map<String, List<Cookie>> cookieStore = new ConcurrentHashMap<>();

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        LOGGER.trace("保存cookie: from {} cookie {}", url, cookies);
        cookieStore.put(url.host(), cookies);
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.getOrDefault(url.host(), new ArrayList<>());

        LOGGER.trace("加载cookie: from {} cookie {}", url, cookies);

        return cookies;
    }
}
